import api from "../index.js";
import {
	ElMessage
} from "element-plus"
import store from "../../store/index.js";
import router from "../../router/index.js";

const inn = (user) => {
	window.localStorage.removeItem("token")
	if (window.localStorage.getItem("token")) {
		ElMessage.error('已有账号，请退出后再尝试')
		return
	}
	if (user.username == '' || user.username == undefined) {
		ElMessage.warning('请输入账号')
		return
	}
	if (user.password == '' || user.password == undefined) {
		ElMessage.warning('请输入密码')
		return
	}

	const fd = new FormData
	fd.append('username', user.username)
	fd.append("password", user.password)

	api.postf('/log/in', fd).then((resp) => {
		let token = resp.data.data.token

		if (!token) {
			ElMessage.error(resp.data.msg)
			window.localStorage.removeItem("token", '')
			return
		}
		console.log("token -----: " + token)
		window.localStorage.setItem("token", token)
		api.get("/api/user/info").then((resp) => {
			store.state.user.account = resp.data.data.account
			store.state.user.img = resp.data.data.img
			store.state.user.name = resp.data.data.nickname
			store.state.user.role = resp.data.data.role

			window.localStorage.setItem('account', store.state.user.account)
			window.localStorage.setItem('img', store.state.user.img)
			window.localStorage.setItem('name', store.state.user.name)
			window.localStorage.setItem('role', store.state.user.role)
			// 判断用户是否存在有相应的角色-->跳转
			if (resp.data.data.role === 'usr') {
				router.push("/welcome")
				return
			}
			router.push("/adm/index")
		})
	})
}

const out = () => {
	if (!window.localStorage.getItem('token')) {
		ElMessage.warning("用户未登录");
		return;
	}
	window.localStorage.removeItem("role")
	window.localStorage.removeItem("name")
	window.localStorage.removeItem("img")
	window.localStorage.removeItem("account")
	window.localStorage.removeItem("token")
	store.state.user.account = undefined
	store.state.user.img = undefined
	store.state.user.name = undefined
	store.state.user.role = undefined

	api.get('/log/out').then((resp) => {
		ElMessage.success(resp.data.msg)
		router.push('/login')

	})
}

export default {
	inn,
	out
}